package com.aliang.chat.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.aliang.chat.contact.StaticContact;
import com.aliang.chat.enums.MessageTypeEnum;
import com.aliang.chat.mapper.ContactMapper;
import com.aliang.chat.mapper.MessageMapper;
import com.aliang.chat.mapper.UserMapper;
import com.aliang.chat.model.dto.MessageDTO;
import com.aliang.chat.model.entity.Contact;
import com.aliang.chat.model.entity.Message;
import com.aliang.chat.model.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private ContactMapper contactMapper;
    @Resource
    private UserMapper userMapper;

    public List<MessageDTO> getMessageList(Integer userId, Integer contactId) {
        //根据用户id和联系人id查询联系人
        Contact contact = contactMapper.selectByUserIdAndContactId(userId, contactId);
        if (contact == null) {
            return null;
        }
        //根据两个用户Id查询用户数据并以用户Id为键存入map中
        Map<Integer, User> userMap = userMapper.selectByUserIds(Arrays.asList(userId, contactId))
                .stream().collect(Collectors.toMap(User::getId, user -> user));
        //更新联系人未读消息为0
        contactMapper.updateUnreadByContactId(contact.getContactId());
        //根据用户id和联系人id查询消息
        List<Message> messageList = messageMapper.getMessageListByUserIdAndContactId(userId, contact.getId());
        //转换为vo
        return messageList.stream().map(message -> {
            MessageDTO messageDTO = new MessageDTO();
            BeanUtils.copyProperties(message, messageDTO);
            messageDTO.setFromUser(userMap.get(message.getFromId()));
            return messageDTO;
        }).collect(Collectors.toList());
    }


    public void addMessage(MessageDTO messageDTO) {
        Message message = new Message();
        BeanUtils.copyProperties(messageDTO, message);
        message.setFromId(messageDTO.getFromUser().getId());
        messageMapper.addMessage(message);
    }


    public boolean delete(MessageDTO messageDTO) {
        if (!MessageTypeEnum.TEXT.getType().equals(messageDTO.getType())) {
            //不是文本文件，需要删除文件
            List<String> list = JSONUtil.toList(messageDTO.getContent(), String.class);
            for (String fileName : list) {
                fileName = fileName.substring(StaticContact.httpFilePath.length());
                FileUtil.del(StaticContact.filePath + fileName);
            }
        }
        return messageMapper.deleteMessage(messageDTO.getId()) > 0;
    }
}
